const jwt = require("jsonwebtoken")

const UserModel = require("./UserModel")

const SECRET = "ydfdvnreuvuidfngleodv"
module.exports = async function (req, res, next) {
  const raw = String(req.headers["authorization"]).split(" ").pop()
  if (!raw) {
    res.status(401)
    return res.json({ msg: "无token，请重新登录" })
  }
  try {
    const token = jwt.verify(raw, SECRET)
    console.log(token)
    if (!token || token.exp <= Date.now() / 1000) {
      res.status(401)
      return res.json({ msg: "token过期" })
    } else {
      const id = token.id
      req.user = await UserModel.findById(id)
    }
    next()
  } catch (error) {
    console.log(error)
    res.send({ status: 1, msg: "出异常了" })
  }
}
